# -*- coding: utf-8 -*-
#from __future__ import with_statement
from Tkinter import *
from builders import *
import sys
import os
sys.path.append(os.path.abspath('..'))
from service.PlusterLog import *
#from service.Log import *



#
## Class mastering all stuff.
class VBtk(object):

    def _objbegin(self, line):

        if re.search('Begin (VB|TabDlg).', line):
            return True
        else:
            return False

    def _objend(self, line):
        if 'End' in line:
            return True
        else:
            return False

    def BuildObj(self, bgline, father):
        """-> a builder object."""
        tmp = bgline.split()
        vbobjname = tmp[-1]
        vbobjtype = tmp[-2]
        # print vbobjname, vbobjtype
        builder = self.GetBuilder(vbobjtype)
        if builder:
            rt = builder(father)
            rt.name = vbobjname
            return rt
        else:
            return None

    def _buildwidgeteventcallbacktable(self):
        emt = dict(
            Click     = '<Button-1>',
            DblClick  = '<Double-Button-1>'
            )
        try:
            self.wecbt = dict([(i.__name__.split('_')[1],(emt[i.__name__.split('_')[2]],i)) for i in [i for i in filter(callable,[getattr(self,i) for i in dir(self)])] if i.__name__.find('WECB') == 0])
        except LookupError:
            self.log.warning('[VBtk._buildw...] A LookupError i.__name__=%s' % i.__name__)
            pass



    def AutoBind(self, wobj, wobjname):

        if self.wecbt == {}:
            self._buildwidgeteventcallbacktable()

        try:
            wobj.bind(self.wecbt[wobjname][0],self.wecbt[wobjname][1])
        except KeyError:
            pass

    def Scan(self, lines, master=None):

        olist = []

        class Foo:
            def GetWobj(self, dummy=None):
                return master

        olist.append((-1, Foo()))
        i=0
        while i < len(lines):
            if self._objbegin(lines[i]):
                # print 'start begin block'
                wbobj = self.BuildObj(lines[i], olist[-1][1].GetWobj())
                olist.append((i, wbobj))
                i+=1
            elif self._objend(lines[i]):
                # print 'start end block'
                tmp = olist.pop()
                bgi = tmp[0]
                edi = i
                wbobj = tmp[1]

                wobj = wbobj.SetConfig(lines[bgi+1:edi])
                topwobj = olist[-1][1].GetWobj(wbobj)

                if wobj:
                    #print wobj.name,topwobj
                    setattr(topwobj, wbobj.name, wobj)
                    self.AutoBind(wobj, wbobj.name)

                lines = lines[:bgi]+lines[edi+1:]

                i = bgi - 1
                if len(olist)<=1:
                    return
            else:
                i+=1


    def GetBuilder(self, vbwidgetname):
        """-> WidgetBuilder. Control name in VB as input.
        For 'VB.TextBox', will return, if any, a classobj
        of TextBoxBuilder deriving from WidgetBuilder.
        """

        # if a custom typefunmap is defined, will return
        # custom widget-builder
        try:
            if self.typefunmap.has_key(vbwidgetname):
                return self.typefunmap[vbwidgetname]
        except AttributeError:
            #self.log.warning('[VBtk.GetBuilder] no typefunmap found, will searching in default builders.')
            pass

        # vbwidgetname must in a fashion like 'VB.Something'
        try:
            buildername = vbwidgetname.split('.')[1] + 'Builder'
            builder = getattr(sys.modules[__name__], buildername)
            # print vbwidgetname, builder
            return builder
        except IndexError:
            self.log.warning('[VBtk.GetBuilder] parse buildername error.')
        except AttributeError:
            print buildername
        return None

    def LoadFrm(self, filename, master=None):
        self.master = master
        self.wecbt = {}

        fh=open("./form/"+filename,'r')
        filebody = fh.readlines()
        fh.close()
        self.Scan(filebody, master)


